package cn.edkuir.auth.controller;

import cn.edkuir.auth.feign.MemberFeignService;
import cn.edkuir.auth.feign.ThirdPartyFeignService;
import cn.edkuir.auth.vo.UserLoginVo;
import cn.edkuir.auth.vo.UserRegisterVo;
import cn.edkuir.common.constant.AuthServerConstant;
import cn.edkuir.common.exception.BizCodeEnum;
import cn.edkuir.common.utils.R;
import cn.edkuir.common.vo.MemberRespVo;
import com.alibaba.fastjson.TypeReference;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Controller
public class LoginController {
    @Autowired
    private ThirdPartyFeignService thirdPartyFeignService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private MemberFeignService memberFeignService;


    /**
     * 发送一个请求直接跳转到一个页面
     * springmvc viewController 将请求和页面映射过来
     */
    @GetMapping("/login.html")
    public String loginPage(HttpSession session) {
        Object user = session.getAttribute(AuthServerConstant.LOGIN_USER);
        if(user == null) {
            //用户没登录
            return "login";
        }
        return "redirect:http://mall.com";
    }


//    @GetMapping("/register.html")
//    public String registerPage() {
//        return "register";
//    }


    @GetMapping("/sms/sendcode")
    @ResponseBody
    public R sendCode(@RequestParam("phone") String phone) {
        //1.接口防刷
        String redisCode = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
        if(!StringUtils.isEmpty(redisCode)) {
            long t = Long.parseLong(redisCode.split("_")[1]);
            if(System.currentTimeMillis() - t < 60000) {
                //60min内不能再发
                return R.error(BizCodeEnum.VALID_SMS_CODE_EXCEPTION.getCode(), BizCodeEnum.VALID_SMS_CODE_EXCEPTION.getMessage());
            }
        }

        //2.验证码的再次校验 redis: 存key-phone, value-code (sms:code:18810323057 -> 123456)
        String code = UUID.randomUUID().toString().substring(0, 5) + "_" + System.currentTimeMillis();
        //redis缓存十分钟
        stringRedisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone, code, 10, TimeUnit.MINUTES);

        thirdPartyFeignService.sendCode(phone, code.split("_")[0]);
        return R.ok();
    }


    /**
     * 重定向携带数据, 将数据放在session中, 只要跳到下一个页面取出这个数据后, session里面的数据就会被删掉
     * TODO 分布式下的session问题
     */
    @PostMapping("/register")
    public String register(@Valid UserRegisterVo userRegisterVo, BindingResult result, RedirectAttributes redirectAttributes) {
        if(result.hasErrors()) {
            Map<String, String> errors = result.getFieldErrors().stream()
                    .collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            redirectAttributes.addFlashAttribute("errors", errors);

            //校验出错, 转发到注册页
            //return "forward:/register.html";
            //注意这里不能写forward, 路径映射只能是get请求方式, 而注册请求是post
            return "redirect:http://auth.mall.com/register.html";
        }

        //注册
        //1.校验验证码
        String code = userRegisterVo.getCode();
        String phone = userRegisterVo.getPhone();
        String s = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
        if(!StringUtils.isEmpty(s)) {
            if(code.equals(s.split("_")[0])) {
                //验证码通过
                //2.删除验证码
                stringRedisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);

                //3.远程调用会员模块进行注册
                R r = memberFeignService.register(userRegisterVo);
                if((int) r.get("code") != 0) {
                    Map<String, String> errors = new HashMap<>();
                    errors.put("msg", r.getData("msg", new TypeReference<String>(){}));
                    redirectAttributes.addFlashAttribute("errors", errors);
                    return "redirect:http://auth.mall.com/register.html";
                }

            }else {
                Map<String, String> errors = new HashMap<>();
                errors.put("code", "验证码错误");
                redirectAttributes.addFlashAttribute("errors", errors);
                return "redirect:http://auth.mall.com/register.html";
            }
        }else {
            Map<String, String> errors = new HashMap<>();
            errors.put("code", "验证码错误");
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.mall.com/register.html";
        }

        return "redirect:http://auth.mall.com/login.html";
    }



    @PostMapping("/login")
    public String login(UserLoginVo userLoginVo, RedirectAttributes redirectAttributes, HttpSession session) {
        R r = memberFeignService.login(userLoginVo);
        if((int) r.get("code") == 0) {
            //TODO 登录成功后的处理
            MemberRespVo data = r.getData(new TypeReference<MemberRespVo>(){});
            System.out.println(data);
            session.setAttribute(AuthServerConstant.LOGIN_USER, data);
            return "redirect:http://mall.com";
        }

        Map<String, String> errors = new HashMap<>();
        errors.put("msg", r.getData("msg", new TypeReference<String>(){}));
        redirectAttributes.addFlashAttribute("errors", errors);

        return "redirect:http://auth.mall.com/login.html";
    }


}
